package cn.aaalei.shorturl.receiver;


import cn.aaalei.shorturl.mapper.UrlMapper;
import cn.aaalei.shorturl.pojo.UrlLogging;
import cn.aaalei.shorturl.utils.HttpUtils;
import com.alibaba.fastjson.JSONObject;
import nl.basjes.parse.useragent.UserAgent;
import nl.basjes.parse.useragent.UserAgentAnalyzer;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
@RabbitListener(queues = "WebLogDirectQueue")//监听的队列名称 WebLogDirectQueue
public class DirectReceiver {

    @Autowired
    private UrlMapper urlMapper;

    @RabbitHandler
    public void process(Map webLogMessage) throws ParseException {
        Long beginTime = System.currentTimeMillis();
        System.out.println("DirectReceiver消费者收到消息  : " + webLogMessage.toString());
        String ipAddress = (String) webLogMessage.get("messageIPAddress");
        String host = "https://hcapi22.market.alicloudapi.com";
        String path = "/ip";
        String method = "GET";
        String appcode = "f70c4aba4727479ca3d4f5bfd92612d0";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("ip", ipAddress);

        JSONObject jsonObject = null;
        if(!ipAddress.equals("0:0:0:0:0:0:0:1")){
            try {
                /**
                 * 重要提示如下:
                 * HttpUtils请从
                 * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
                 * 下载
                 *
                 * 相应的依赖请参照
                 * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
                 */
                HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
//            System.out.println(EntityUtils.toString(response.getEntity()));
                jsonObject = JSONObject.parseObject(EntityUtils.toString(response.getEntity()));
                //获取response的body
                //System.out.println(EntityUtils.toString(response.getEntity()));
            } catch (Exception e) {
                e.printStackTrace();
            } }

        //UAA
        UserAgentAnalyzer uaa = UserAgentAnalyzer
                .newBuilder()
                .hideMatcherLoadStats()
                .withCache(10000)
                .build();
        UserAgent agent = uaa.parse((String) webLogMessage.get("messageData"));

        UrlLogging urlLogging = new UrlLogging();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = dateFormat.parse((String) webLogMessage.get("createTime"));
        urlLogging.setTimestamp(date);
        urlLogging.setShortUrl((String) webLogMessage.get("messageShort"));
        if(ipAddress.equals("0:0:0:0:0:0:0:1")){
            //处理本地
            urlLogging.setIp("0:0:0:0:0:0:0:1");
            urlLogging.setCountry("本地");
            urlLogging.setArea("本地");
            urlLogging.setRegion("本地");
            urlLogging.setCity("本地");
            urlLogging.setIsp("本地网络");
            urlLogging.setOriginIpInformation("本地网络");
        }else if (jsonObject.getString("ret").equals("200")){
            String data = jsonObject.getString("data");
            urlLogging.setIp(JSONObject.parseObject(data).getString("ip"));
            urlLogging.setCountry(JSONObject.parseObject(data).getString("country"));
            urlLogging.setArea(JSONObject.parseObject(data).getString("area"));
            urlLogging.setRegion(JSONObject.parseObject(data).getString("region"));
            urlLogging.setCity(JSONObject.parseObject(data).getString("city"));
            urlLogging.setIsp(JSONObject.parseObject(data).getString("isp"));
            urlLogging.setOriginIpInformation(jsonObject.toString());
        }
        if (agent.getValue("OperatingSystemClass").equals("Desktop")){
            urlLogging.setDeviceClass(agent.getValue("OperatingSystemName"));
        }else if(agent.getValue("OperatingSystemName").equals("Android")){
            urlLogging.setDeviceClass("Android");
            urlLogging.setDeviceName(agent.getValue("DeviceName"));
        }else if(agent.getValue("OperatingSystemName").equals("iOS")){
            urlLogging.setDeviceClass(agent.getValue("DeviceVersion"));
            urlLogging.setDeviceName(agent.getValue("DeviceName"));
        }else {
            urlLogging.setDeviceClass("unknown");
        }
        urlLogging.setOriginUa((String) webLogMessage.get("messageData"));
        urlLogging.setAgentName(agent.getValue("AgentName"));
        urlMapper.addUrlLogging(urlLogging);
        Long endTime = System.currentTimeMillis();
        System.out.println("插入消耗时间：" + (endTime - beginTime) + "ms");
    }
}